<template>
  <nav-bar title="完善发货信息"></nav-bar>
  <div class="main">
    <!-- <van-form class="form" @submit="onSubmit"> -->
    <van-form @submit="confirmOrder" ref="formRef">
      <div class="form">
        <van-field
          v-model="goodsName"
          name="goodsName"
          label="货物名称"
          placeholder="请输入货物名称(必填)"
          :rules="[{ required: true, trigger: 'onChange', message: '请输入货物名称' }]"
        />
        <van-field
          v-model="goodsType"
          name="goodsType"
          readonly
          clickable
          is-link
          label="货物类型"
          input-align="left"
          placeholder="请选择货物类型"
          @click="goodsTypePicker = true"
          :rules="[{ required: true, trigger: 'onChange', message: '请选择货物类型' }]"
        />
        <van-field
          v-model="quality"
          name="quality"
          type="number"
          label="重量/吨"
          placeholder="请输入重量(必填)"
          :rules="[
            { required: true, trigger: 'onChange', message: '请输入重量' },
            { validator, trigger: 'onChange', message: '重量最大值为50.00' }
          ]"
        />
        <van-field v-model="goodsVolume" name="address" type="number" label="体积/立方" placeholder="请输入体积" />
        <van-field
          v-model="carType"
          name="carType"
          readonly
          clickable
          is-link
          placeholder="请选择车长车型"
          label="车长车型"
          input-align="left"
          @click="carTypePicker = true"
          :columns-field-names="{
            text: 'label',
            values: 'label'
          }"
          :rules="[{ required: true, trigger: 'onChange', message: '请选择车长车型' }]"
        />
        <van-field name="radio" label="计算方式">
          <template #input>
            <van-radio-group v-model="settleType" name="settleType" direction="horizontal">
              <van-radio name="1">趟</van-radio>
              <van-radio name="2">吨</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="price"
          name="price"
          type="number"
          label="我的出价"
          placeholder="请输入运费(必填)"
          :rules="[{ required: true, trigger: 'onChange', message: '请输入运费' }]"
        >
          <template #extra>元/{{ settleType === '1' ? '趟' : '吨' }}</template>
        </van-field>
        <van-field
          v-model="payType"
          name="payType"
          readonly
          clickable
          is-link
          label="结算方式"
          input-align="left"
          placeholder="请选择结算方式"
          @click="payTypePicker = true"
          :rules="[{ required: true, trigger: 'onChange', message: '请选择结算方式' }]"
        />
        <van-field
          v-model="remark"
          name="remark"
          class="remark"
          rows="1"
          autosize
          label="备注"
          type="textarea"
          maxlength="50"
          placeholder="给司机捎句话…"
          show-word-limit
        />
      </div>

      <div class="agreement">
        <van-checkbox v-model="isChecked" icon-size="12px" shape="square"></van-checkbox>
        <p>我已阅读并同意</p>
        <span @click="goPage('TransportServicesAgreement')">《货物运输协议》</span>
        <span @click="goPage('TechnicalServiceAgreement')">《货物运输技术服务协议》</span>
      </div>
      <!-- <van-button type="primary" class="button">确认装货地址</van-button> -->
      <div class="main_bottom">
        <van-button type="primary" class="button_left" @click="goAssignOrder">指定承运人</van-button>
        <van-button type="primary" class="button_right" native-type="submit">确认发货</van-button>
      </div>
    </van-form>
  </div>
  <van-popup v-model:show="goodsTypePicker" position="bottom">
    <van-picker :columns="goodsTypeOptions" @cancel="goodsTypePicker = false" @confirm="onGoodsTypeConfirm" />
  </van-popup>
  <van-popup v-model:show="payTypePicker" position="bottom">
    <van-picker :columns="payTypeOptions" @cancel="payTypePicker = false" @confirm="onPayTypeConfirm" />
  </van-popup>
  <van-popup v-model:show="carTypePicker" position="bottom">
    <van-picker :columns="carTypeColumns" @confirm="onCarTypeConfirm" @cancel="carTypePicker = false" />
  </van-popup>
  <van-popup v-model:show="passwordPoppup" position="bottom">
    <div class="passwordPoppup">
      <div class="memo">请输入支付密码</div>
      <van-password-input :value="payPassword" :focused="true" />
      <van-number-keyboard
        v-model="payPassword"
        :show="true"
        @input="prePayType"
        maxlength="6"
        @blur="passwordPoppup = false"
      />
    </div>
  </van-popup>
</template>

<script lang="ts">
import navBar from '@/components/NavBar.vue'
import { reactive, toRefs, ref, unref, onMounted } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { api } from '@/http/api'
import http from '@/http'
import store from '@/store/index'
import { Toast, FormInstance } from 'vant'

type SelectedOption = {
  text: string
  value: string | number
}
export default {
  name: 'DeliveryInfo',
  components: {
    navBar
  },
  setup() {
    const route = useRoute(),
      router = useRouter()
    const formRef = ref<FormInstance>()
    const validator = (val: any) => {
      if (val > 50) {
        state.quality = '50.00'
        return false
      }
      return true
    }
    const state = reactive({
      goodsTypePicker: false,
      payTypePicker: false,
      carTypePicker: false,
      passwordPoppup: false,
      isChecked: true,
      goodsTypeOption: {} as SelectedOption,
      goodsType: '',
      goodsName: '',
      quality: '',
      goodsVolume: '',
      carTypeArr: [] as any[],
      carType: '',
      settleType: '1',
      price: '',
      payTypeOption: {} as SelectedOption,
      payType: '',
      remark: '',
      payPassword: ''
    })
    const option = reactive({
      carTypeColumns: [] as any[],
      goodsTypeOptions: [] as any[],
      payTypeOptions: [] as any[]
    })

    const onGoodsTypeConfirm = (values: SelectedOption) => {
      state.goodsTypePicker = false
      state.goodsType = values.text
      state.goodsTypeOption = values
    }

    const onPayTypeConfirm = (values: any) => {
      state.payTypePicker = false
      state.payType = values.text
      state.payTypeOption = values
    }

    const onCarTypeConfirm = (values: any[]): void => {
      state.carTypeArr = values
      state.carType = values.map(item => item.text).join(' ')
      state.carTypePicker = false
    }
    const baseInfo = route.params.baseInfo && JSON.parse(route.params.baseInfo as string)

    //预付时弹出输入支付密码
    const prePayType = (value: string) => {
      const password: string = state.payPassword + value
      const { params, baseParams } = handleData()
      if (password.length === 6) {
        //校验支付密码
        http<string>({
          url: api.payPasswordCheck,
          method: 'get',
          params: { payPassword: password }
        })
          .then((res: any) => {
            if (res) {
              //生成订单
              http<string>({
                url: api.transportOrderAdd,
                method: 'post',
                data: Object.assign(params, baseParams)
              }).then((res: any) => {
                //扣款
                http<string>({
                  url: api.transportOrderPayment,
                  method: 'post',
                  data: { orderId: res, password }
                }).then(() => {
                  router.push({ name: 'Waybill' })
                  store.commit('cachedView/clearCachedItem', { name: 'Delivery' })
                  Toast.success('发货成功')
                  state.passwordPoppup = false
                })
              })
            } else {
              Toast.fail('支付密码错误')
            }
          })
          .catch(error => {
            Toast.fail('未设置支付密码')
          })
      }
    }
    //整理数据
    const handleData = () => {
      const baseParams = {
        sendProvinceName: baseInfo.startInfo.addressArr[0].name,
        sendProvinceCode: baseInfo.startInfo.addressArr[0].id,
        sendCityName: baseInfo.startInfo.addressArr[1].name,
        sendCityCode: baseInfo.startInfo.addressArr[1].id,
        sendCountyName: baseInfo.startInfo.addressArr[2].name,
        sendCountyCode: baseInfo.startInfo.addressArr[2].id,
        receiveProvinceName: baseInfo.endInfo.addressArr[0].name,
        receiveProvinceCode: baseInfo.endInfo.addressArr[0].id,
        receiveCityName: baseInfo.endInfo.addressArr[1].name,
        receiveCityCode: baseInfo.endInfo.addressArr[1].id,
        receiveCountyName: baseInfo.endInfo.addressArr[2].name,
        receiveCountyCode: baseInfo.endInfo.addressArr[2].id,
        sendName: baseInfo.startInfo.name,
        sendMobile: baseInfo.startInfo.phone,
        sendDetailAddress: baseInfo.startInfo.detailAddress,
        receiveName: baseInfo.endInfo.name,
        receiveMobile: baseInfo.endInfo.phone,
        receiveDetailAddress: baseInfo.endInfo.detailAddress,
        shipTime: baseInfo.startDate,
        unloadTime: baseInfo.endDate,
        sendLongitude: baseInfo.endInfo.addressLongitude,
        sendLatitude: baseInfo.endInfo.addressLatitude,
        receiveLongitude: baseInfo.startInfo.addressLongitude,
        receiveLatitude: baseInfo.startInfo.addressLatitude
      }
      const totalPrice = state.settleType === '1' ? state.price : parseInt(state.price) * parseInt(state.quality)
      // pointType	指派方式（字典 1派单 2抢单）
      const params: any = {
        goodsName: state.goodsName,
        goodsType: state.goodsTypeOption.value,
        goodsVolume: state.goodsVolume,
        quality: state.quality,
        vehicleLong: state.carTypeArr[0].value,
        vehicleType: state.carTypeArr[1].value,
        settleType: state.settleType,
        totalAllot: state.settleType === '1' ? 1 : state.quality,
        price: state.price,
        totalPrice,
        payType: state.payTypeOption.value,
        remark: state.remark,
        pointType: 2,
        sendFlag: 'N',
        receiveFlag: 'N',
        carrierFlag: 'N'
      }

      if (params.payType === '1') {
        params.prepaymentRatio = 100 //预付比例
      } else if (params.payType === '2') {
        params.payRatio = 100 //到付比例
      } else if (params.payType === '3') {
        params.settleRatio = 100 //月结比例
      } else if (params.payType === '4') {
        params.receiptRatio = 100 //回单付比例
      }
      return { params, baseParams }
    }
    //确定发货
    const confirmOrder = async (value: string) => {
      if (!state.isChecked) {
        Toast.fail('请阅读并同意协议!')
        return false
      }
      const { params, baseParams } = handleData()
      // if (params.payType === '1') {
      //   // 显示密码输入框
      //   state.passwordPoppup = true
      // } else {
      http<string>({
        url: api.transportOrderAdd,
        method: 'post',
        data: Object.assign(params, baseParams)
      }).then((res: any) => {
        router.push({ name: 'Waybill' })
        store.commit('cachedView/clearCachedItem', { name: 'Delivery' })
        Toast.success('发货成功')
      })
      // }
    }
    //指派订单给承运商或司机
    const goAssignOrder = () => {
      formRef.value?.validate().then(res => {
        if (!state.isChecked) {
          Toast.fail('请阅读并同意协议!')
          return false
        }
        const { params, baseParams } = handleData()
        router.push({
          name: 'AssignOrder',
          params: { params: JSON.stringify(Object.assign(params, baseParams)) }
        })
      })
    }
    // 页面跳转
    const goPage = (name: string): void => {
      router.push({
        name
      })
    }

    onBeforeRouteLeave((to, from, next) => {
      if (to.name !== 'AssignOrder') {
        store.commit('cachedView/clearCachedItem', from)
      }
      next()
    })

    const asyncOption = async () => {
      const options = await store.dispatch('system/handleGetDictTypeGetByDictType', {
        dictTypeCode: 'VEHICLE_TYPE,CAR_LENGTH,GOODS_TYPE,SETTLE_TYPE'
      })
      options['CAR_LENGTH'].map((item: any) => {
        item.text = `${item.text}米`
      })
      option.carTypeColumns = [
        {
          values: options['CAR_LENGTH']
        },
        {
          values: options['VEHICLE_TYPE']
        }
      ]
      option.goodsTypeOptions = options['GOODS_TYPE']
      const result: any = await http<string>({
        url: api.getSimpleConsignerUser,
        method: 'get'
      })
      option.payTypeOptions = []
      if (result && result.length > 0) {
        const arr = result[0].settleType.split(',')
        for (const item of arr) {
          options['SETTLE_TYPE'].forEach((element: any) => {
            if (element.code === item) {
              option.payTypeOptions.push(element)
            }
          })
        }
      }
    }

    onMounted(() => {
      asyncOption()
    })

    return {
      ...toRefs(state),
      ...toRefs(option),
      formRef,
      onGoodsTypeConfirm,
      onPayTypeConfirm,
      onCarTypeConfirm,
      confirmOrder,
      goPage,
      goAssignOrder,
      prePayType,
      validator
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/style/variables.scss';
@import '@/style/mixins.scss';
.main {
  width: 100%;
  min-height: $main-min-height;
  background: $background-color-base;
  position: relative;
}
.form {
  box-shadow: 0px 6px 14px 0px rgba(221, 221, 221, 0.15);
  border-radius: 10px;
  overflow: hidden;
  margin: 15px 12px 0 12px;
}
.button {
  margin-top: 100px;
  margin-left: 14px;
  width: 325px;
  height: 48px;
}
.remark {
  flex-direction: column;
  align-items: flex-start !important;
  ::v-deep(.van-cell__value) {
    width: 100% !important;
  }
}
.agreement {
  margin: 10px 0 0 14px;
  font-size: 10px;
  box-sizing: border-box;
  line-height: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  span {
    color: $color-primary;
  }
  p {
    color: $color-text-regular;
    padding-left: 5px;
  }
}
.main_bottom {
  height: 74px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #fff;
  > .button_left {
    width: 142px;
    height: 40px;
    border-radius: 24px;
    border: 1px solid $color-primary;
    background: #fff;
    color: $color-primary;
  }
  .button_right {
    width: 142px;
    height: 40px;
    box-shadow: 0px 3px 12px 0px rgba(64, 158, 255, 0.4);
    border-radius: 24px;
  }
}
.passwordPoppup {
  width: 100%;
  padding-top: 30px;
  height: 355px;
  .memo {
    text-align: center;
    font-size: 14px;
    margin-bottom: 10px;
    color: #333;
  }
}

::v-deep(.van-cell) {
  padding: 10px;
  min-height: 50px;
  display: flex;
  align-items: center;
}
::v-deep(.van-field__control::-webkit-input-placeholder) {
  font-size: 14px;
  color: $color-text-secondary;
}
::v-deep(.van-cell__right-icon) {
  color: $color-text-regular;
  font-size: 12px;
}
</style>
